package org.apogeescience.connector.databases;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import org.apogeescience.annotation.NamedQuery;
import org.apogeescience.config.DatabaseConfiguration;
import org.apogeescience.connector.DatabaseConnector;

class SqlServerDatabase implements IDatabase {
	
	private DatabaseConnector dbConn;
	private Connection con = null;
	private boolean initialized = false;
	
	private DatabaseConfiguration dbConfig;

	protected SqlServerDatabase(DatabaseConfiguration config) {
		this.dbConfig = config;
		try {
			this.dbConn = new DatabaseConnector(config);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public boolean initialize() {
		if (this.initialized) return true;

		try {
			Class.forName(this.dbConn.getDriver()).newInstance();
			this.con = DriverManager.getConnection(this.dbConn.getConnection(), this.dbConfig.getDatabaseUserName(), 
					this.dbConfig.getDatabasePassword());
			return true;
		} catch (Exception ex) {

		}

		return false;
	}

	@Override
	public Map<String, List<Object>> executeQuery(StringBuilder query) {
		
		try {
			Statement stmt = this.con.createStatement();
			ResultSet set = stmt.executeQuery(query.toString());
			
			ResultSetMetaData metaData = set.getMetaData();
			
			int columns = metaData.getColumnCount();
			
			Map<String, List<Object>> map = new HashMap<>(columns);
			
			for (int i = 1; i <= columns; ++i) {
				map.put(metaData.getColumnName(i), new ArrayList<>());
			}
			
			while(set.next()) {
				for(int i = 1; i <= columns; ++i) {
					map.get(metaData.getColumnName(i)).add(set.getObject(i));
				}
			}
			
			return map;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public String generateQuery(String tableName, NamedQuery namedQuery,
			Hashtable<String, Object> parameters) {
		// TODO Auto-generated method stub
		return null;
	}
}
